package cn.yunyichina.scheduler.jobs.service.clinic.impl;

import java.util.*;

import cn.yunyichina.provider.framework.dubbo.service.*;
import cn.yunyichina.provider.iface.entity.base.RuleResponseDto;
import cn.yunyichina.provider.iface.entity.hisiface.bed.DepositSettlementRecordsVo;
import cn.yunyichina.provider.iface.entity.hisiface.bed.DepositSettlementRecordsVoResponse;
import cn.yunyichina.provider.iface.entity.hisiface.register.RegisterExceptionRecordVo;
import cn.yunyichina.provider.iface.entity.hisiface.register.RegisterExceptionRecordVoResponse;
import cn.yunyichina.utils.commons.StringUtils;
import cn.yunyichina.utils.log.Log;
import cn.yunyichina.utils.log.constant.LogParamType;
import cn.yunyichina.utils.log.constant.LogScene;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import cn.yunyichina.provider.iface.entity.base.OrderExceptionVo;
import cn.yunyichina.provider.iface.entity.base.OrderExtVo;
import cn.yunyichina.provider.iface.entity.base.RuleDto;
import cn.yunyichina.provider.iface.entity.common.ResCommon;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.provider.iface.entity.hisiface.bed.DepositRecordsVo;
import cn.yunyichina.provider.iface.entity.hisiface.bed.DepositRecordsVoResponse;
import cn.yunyichina.provider.iface.entity.hisiface.clinic.PayVo;
import cn.yunyichina.provider.iface.entity.hisiface.clinic.PayVoResponse;
import cn.yunyichina.provider.iface.entity.pay.PaymentJournalVo;
import cn.yunyichina.scheduler.jobs.service.clinic.ClinicExceptionOrderHandlerService;
import cn.yunyichina.utils.commons.DateUtils;
import cn.yunyichina.utils.convert.JsonUtils;
import cn.yunyichina.utils.convert.ObjectParser;

/**
 * 作者：彭剑平
 * 修改：zhangkewen
 * 修改时间：20170726
 */
@Service
public class ClinicExceptionOrderHandlerServiceImpl implements ClinicExceptionOrderHandlerService {

    private static final Logger logger = LoggerFactory.getLogger(ClinicExceptionOrderHandlerServiceImpl.class);

    //默认最小异常的查询次数
    private static final int HIS_QUERY_NORMAL_EXCEPTION_MIN_NUM=1;

    //默认最小异常的查询Key字符串
    private static final String HIS_QUERY_NORMAL_EXCEPTION_MIN_KEY_STR="MINQUERY";
    
    //默认最大异常的查询次数
    private static final int QUERY_EXCEPTION_MAX_NUM=24;

    //默认最大异常的查询Key字符串
    private static final String QUERY_EXCEPTION_MAX_KEY_STR="MAXQUERY";

    //每个异常单处理的间隔时间
    private static  final int exceptionSleepTime=10000;

    @Override
    public void doExecute() {
        String batchNo="YC_HANDLE_"+DateUtils.dateToStringNoFlit(new Date());
        long beginTime = System.currentTimeMillis();
        String prefixLogStr="定时异常单处理[批次:"+batchNo+"]||";
        Log.i(LogScene.EXCEPTION_ORDER_FILTER,"定时异常单处理开始处理,处理批次:"+batchNo);

    	//查询需要异常处理的订单 
    	//查询条件：1.自费退款标记未处理& 2.医保退款未处理& 3.His查询状态未查询& 4.查询的时间间隔为3天
    	OrderExceptionVo orderExceptionVoRequest = new OrderExceptionVo();
    	orderExceptionVoRequest.setSelfPayHandlerFlag((short) 0);
    	orderExceptionVoRequest.setInsuranceHandlerFlag((short) 0);
    	orderExceptionVoRequest.setHisQueryState((short) 0);
    	orderExceptionVoRequest.setBeginCreatedTime(DateUtils.getBetweenDay(-3));
    	orderExceptionVoRequest.setEndCreatedTime(DateUtils.dateToString(new Date()));

        Log.i(LogScene.EXCEPTION_ORDER_FILTER,"yyt.base.order.exceptions.list", LogParamType.REQUEST,"",
                prefixLogStr+JSON.toJSONString(orderExceptionVoRequest));
        Response response = BaseService.callUnderlineFromInternal("yyt.base.order.exceptions.list",JsonUtils.toJsonString(orderExceptionVoRequest));
        Log.i(LogScene.EXCEPTION_ORDER_FILTER,"yyt.base.order.exceptions.list", LogParamType.RESPONSE,"",
                prefixLogStr+JSON.toJSONString(response));
        if (!"0".equals(response.getResultCode())) {
            Log.i(LogScene.EXCEPTION_ORDER_FILTER,
                    prefixLogStr+"定时异常单处理完成,查询订单失败,返回错误码:"+response.getResultCode()+",错误理由:"+response.getResultMessage());
            return;
        }

        List<OrderExceptionVo> orderExceptionVos = JsonUtils.parseArray(response.getResult(), OrderExceptionVo.class);
        if (CollectionUtils.isEmpty(orderExceptionVos)) {
            Log.i(LogScene.EXCEPTION_ORDER_FILTER,
                    prefixLogStr+"定时异常单处理完成,查询订单不存在,没有可异常的订单处理!");
            return;
        }
        
        //当前查询次数的缓存
        Map<String,Integer> ruleMaps=new HashMap<String,Integer>();
        
        //循环处理需要处理的订单(订单类型为:挂号  门诊  住院)
        for (OrderExceptionVo orderExceptionVo : orderExceptionVos) {
           //查询该异常订单的订单详情信息
            Map<String, String> dataMap = new HashMap<String, String>();
            dataMap.put("order_no", orderExceptionVo.getOrderNo());

            Log.i(LogScene.EXCEPTION_ORDER_FILTER,"yyt.base.order.by.order.no.out.get", LogParamType.REQUEST,orderExceptionVo.getOrderNo(),
                    prefixLogStr+JSON.toJSONString(dataMap));
            Response ordResponse = BaseService.callUnderlineFromInternal("yyt.base.order.by.order.no.out.get",JsonUtils.toJsonString(dataMap));
            Log.i(LogScene.EXCEPTION_ORDER_FILTER,"yyt.base.order.by.order.no.out.get", LogParamType.RESPONSE,orderExceptionVo.getOrderNo(),
                    prefixLogStr+JSON.toJSONString(ordResponse));
            
            if (!"0".equals(ordResponse.getResultCode())) {
                String reason=prefixLogStr+"查询订单返回失败,失败码:"+ordResponse.getResultCode()+",失败内容:"+ordResponse.getResultMessage()+",该单不处理，继续循环到下一笔订单!";
                Log.i(LogScene.EXCEPTION_ORDER_FILTER, orderExceptionVo.getOrderNo(),reason);
                BaseService.getBaseClient().updateOrderExceptionReason(orderExceptionVo.getId(),orderExceptionVo.getExceptionReason()+"||||"+ reason);
                continue;
            }

            if(StringUtils.isBlank(orderExceptionVo.getOrgCode())){
                String reason=prefixLogStr+"组织机构编码为空，请检查业务方进库数据是否有问题,该订单不进行异常处理!";
                Log.i(LogScene.EXCEPTION_ORDER_FILTER, orderExceptionVo.getOrderNo(),reason);
                BaseService.getBaseClient().updateOrderExceptionReason(orderExceptionVo.getId(),orderExceptionVo.getExceptionReason()+"||||"+ reason);
                continue;
            }

            String hospitalMinQueryMapKey=orderExceptionVo.getOrgCode()+"_"+HIS_QUERY_NORMAL_EXCEPTION_MIN_KEY_STR;
            String hospitalMaxQueryMapKey=orderExceptionVo.getOrgCode()+"_"+QUERY_EXCEPTION_MAX_KEY_STR;
            //查询当前医院的正常需要处理的最小次数才能进行退款
            if(!ruleMaps.containsKey(hospitalMinQueryMapKey)){
                int currentHisQueryNormalMinNum=getAttributeValue(orderExceptionVo.getOrgCode(),"exceptionHisNormalMinNum",HIS_QUERY_NORMAL_EXCEPTION_MIN_NUM,prefixLogStr);
                ruleMaps.put(hospitalMinQueryMapKey,currentHisQueryNormalMinNum);
                Log.i(LogScene.EXCEPTION_ORDER_FILTER, orderExceptionVo.getOrderNo(),prefixLogStr+"查询当前医院["+orderExceptionVo.getOrgCode()+"]的连续HIS返回正常需要处理的最小次数:" + currentHisQueryNormalMinNum);
            }
            //查询医院异常的最大次数
            if(!ruleMaps.containsKey(hospitalMaxQueryMapKey)){
                int currentHisQueryMaxNum=getAttributeValue(orderExceptionVo.getOrgCode(),"exceptionMaxNum",QUERY_EXCEPTION_MAX_NUM,prefixLogStr);
                ruleMaps.put(hospitalMaxQueryMapKey,currentHisQueryMaxNum);
                Log.i(LogScene.EXCEPTION_ORDER_FILTER, orderExceptionVo.getOrderNo(),prefixLogStr+"查询当前医院["+orderExceptionVo.getOrgCode()+"]的异常需要处理的最大次数->" + currentHisQueryMaxNum);
            }

            OrderExtVo order = JsonUtils.parseObject(ordResponse.getResult(), OrderExtVo.class);
            try {
                if(order.getOrderType() == OrderExtVo.ORDER_TYPE_REGISTER){ //挂号订单异常处理 王炜波 挂号所有订单暂时不做处理
                	doRegisterExcepiton(order,orderExceptionVo,ruleMaps.get(hospitalMinQueryMapKey),ruleMaps.get(hospitalMaxQueryMapKey),prefixLogStr);
//                	logger.info("定时异常单处理,查询订单->"+orderExceptionVo.getOrderNo()+"该订单类型为挂号,暂时都当做异常,无须处理,等待规范挂号的返回码!");
                }
                else if (order.getOrderType() == OrderExtVo.ORDER_TYPE_CLINIC) { //门诊异常处理               	
                	doClinicException(order,orderExceptionVo,ruleMaps.get(hospitalMinQueryMapKey),ruleMaps.get(hospitalMaxQueryMapKey),prefixLogStr);
                } else if (order.getOrderType() == OrderExtVo.ORDER_TYPE_IN_HOSPITAL) {//住院异常处理
                	doInHospitalException(order,orderExceptionVo,ruleMaps.get(hospitalMinQueryMapKey),ruleMaps.get(hospitalMaxQueryMapKey),prefixLogStr);
                }else if (order.getOrderType() == OrderExtVo.ORDER_TYPE_OUT_HOSPITAL_SETTLEMENT) {//出院结算异常处理
                    doOutSettlementException(order,orderExceptionVo,ruleMaps.get(hospitalMinQueryMapKey),ruleMaps.get(hospitalMaxQueryMapKey),prefixLogStr);
                }
                else{
                    Log.i(LogScene.EXCEPTION_ORDER_FILTER, orderExceptionVo.getOrderNo(),prefixLogStr + "该订单类型为"+orderExceptionVo.getOrderType()+",没异常处理的逻辑,请跟产品人员联系!");
                }
            } catch (Exception ex) {
                Log.e(LogScene.EXCEPTION_ORDER_FILTER,orderExceptionVo.getOrderNo(),prefixLogStr + "异常单，人工介入查询,异常原因:"+ex.getMessage()+"!",ex);
            }

            try {
                logger.info(prefixLogStr+"线程进入睡眠的时间");
                Thread.sleep(exceptionSleepTime);//睡觉10秒
            } catch (InterruptedException e) {
                logger.error(prefixLogStr+"睡眠异常",e);
            }
        }
        long endTime = System.currentTimeMillis();
        Log.i(LogScene.EXCEPTION_ORDER_FILTER,"定时异常单处理完成,处理批次:"+batchNo+",处理时长:"+(endTime-beginTime)+"毫秒!");
    }
    
    /**
     * 挂号异常处理 该逻辑需要重新梳理
     * @param order
     * @param orderExceptionVo
     */
    private void doRegisterExcepiton(OrderExtVo order, OrderExceptionVo orderExceptionVo, int hisQueryNormalMinNum, int queryMaxExcepionNum, String prefixLogStr) {
        logger.info(prefixLogStr+"挂号异常单处理开始，orderNo=" + order.getOrderNo());
        RegisterExceptionRecordVo registerRecordsVo = new RegisterExceptionRecordVo();
        registerRecordsVo.setHospitalCode(order.getOrgCode());
        registerRecordsVo.setBranchCode(order.getBranchCode());
        registerRecordsVo.setPatCardNo(order.getMedicalCardNo());
        registerRecordsVo.setPatCardType(order.getMedicalCardType() == null ? "1" : String.valueOf(order.getMedicalCardType()));
//        registerRecordsVo.setOrderMode(vo.getPayMode() == null ? "0" : String.valueOf(vo.getPayMode()));
        registerRecordsVo.setOrderMode("0");//orderMode传0 查询所有
        registerRecordsVo.setYytOrdNum(order.getOrderNo());
        Log.i(LogScene.EXCEPTION_ORDER_FILTER_REGISTER,"getRegisterExceptionRecord",LogParamType.REQUEST,
                order.getOrderNo(),prefixLogStr+JSON.toJSONString(registerRecordsVo));
        ResCommon<RegisterExceptionRecordVoResponse> payResponse = HisifaceService.getHisifaceClient().getRegisterExceptionRecord(registerRecordsVo);
        Log.i(LogScene.EXCEPTION_ORDER_FILTER_REGISTER,"getRegisterExceptionRecord",LogParamType.REQUEST,
                order.getOrderNo(),prefixLogStr+JSON.toJSONString(payResponse));

        if ("0".equals(payResponse.getResultCode())) {
            //尝试对his进行多次的查询，才能进行后续的处理
            payResponse = queryHisRegisterResponseMinNum(registerRecordsVo,hisQueryNormalMinNum,prefixLogStr);
            //查询his返回的结果
            if(payResponse!=null && "0".equals(payResponse.getResultCode())){
                RegisterExceptionRecordVoResponse recordsVoResponse= payResponse.getResult();
                if (recordsVoResponse != null && JsonUtils.toJsonString(recordsVoResponse).length() > 5) {
//                    if ("2".equals(recordsVoResponse.getStatus())) { // 查询成功，result值不为空，则当成挂号成功，不判断状态，已与存豪确认;
                        handleRegisterSuccessful(order,orderExceptionVo,recordsVoResponse,prefixLogStr);
                        return;
//                    } else { // 明确失败,查询成功，result为值，但支付状态不是已支付，失败
//                        handleFailure(order, orderExceptionVo, null, true,prefixLogStr);
//                        return;
//                    }
                } else {// 明确失败，查询成功，result为空，认为写单失败，失败
                    handleFailure(order, orderExceptionVo, null, false,prefixLogStr);
                    return;
                }
            }

        } else {
            // 已缴费查询返回不为0，查询失败，等待下次再次查询
            int handleCount = 0;
            if (orderExceptionVo.getExceptionHandlerCount() != null) {
                handleCount = orderExceptionVo.getExceptionHandlerCount().intValue();
            }
            // 处理次数加1
            handleCount++;
            if (handleCount >= queryMaxExcepionNum) {
                String reason=prefixLogStr+"查询挂号订单["+orderExceptionVo.getOrderNo()+"]异常处理超过最大次数:"+queryMaxExcepionNum+"次";
                Log.i(LogScene.EXCEPTION_ORDER_FILTER_REGISTER, orderExceptionVo.getOrderNo(),reason);
                orderExceptionVo.setExceptionReason(orderExceptionVo.getExceptionReason()+"||||"+reason);
                orderExceptionVo.setHisQueryState((short) 3);//his查询异常
                orderExceptionVo.setInsuranceHandlerFlag((short) 3);//无须处理
                orderExceptionVo.setSelfPayHandlerFlag((short) 3);//无须处理
                orderExceptionVo.setHandlerResult((short) 4);//异常单
            } else {
                orderExceptionVo.setExceptionHandlerCount(handleCount);
            }
            updateOrderException(orderExceptionVo);
        }
    }


    /**
     * 门诊异常单处理
     * @param order 订单详情信息
     * @param orderExceptionVo 订单异常信息
     * @param hisQueryNormalMinNum 正常的查询的最小次数
     * @param queryMaxExcepionNum  异常的查询最大次数
     */
    private void doClinicException(OrderExtVo order, OrderExceptionVo orderExceptionVo, int hisQueryNormalMinNum, int queryMaxExcepionNum, String prefixLogStr) {
        //查询HIS已缴费信息查询
        PayVo payvo = new PayVo();
        payvo.setHospitalCode(orderExceptionVo.getOrgCode());
        payvo.setBranchCode(orderExceptionVo.getBranchCode());
        payvo.setPatCardType(ObjectParser.toString(order.getMedicalCardType()));
        payvo.setPatCardNo(order.getMedicalCardNo());
        // 99为海鹚mini付
        payvo.setPayMode(ObjectParser.toString(order.getPayMode().intValue() == 99 ? 23 : order.getPayMode()));
        payvo.setYytOrdNum(orderExceptionVo.getOrderNo());
        Map<String, Object> extendMap = new HashMap<String, Object>();
        extendMap.put("his_ord_num", order.getHisOrderNo());// 佛一门诊已缴费记录查询增加参数
        payvo.setExtendParams(JsonUtils.toJsonString(extendMap));
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, -1);
        payvo.setBeginDate(DateUtils.getDateStr(calendar.getTime()));
        payvo.setEndDate(DateUtils.getDateStr(new Date()));

        Log.i(LogScene.EXCEPTION_ORDER_FILTER_CLINIC,"listClinicPay",LogParamType.REQUEST,
                order.getOrderNo(),prefixLogStr+JSONObject.toJSONString(payvo));
        ResCommon<List<PayVoResponse>> payResponse = HisifaceService.getHisifaceClient().listClinicPay(payvo);
        Log.i(LogScene.EXCEPTION_ORDER_FILTER_CLINIC,"listClinicPay",LogParamType.RESPONSE,
                order.getOrderNo(),prefixLogStr+JSONObject.toJSONString(payResponse));

        if ("0".equals(payResponse.getResultCode())) {
            //尝试对his进行多次的查询，才能进行后续的处理
            payResponse= queryHisClinicResponseMinNum(payvo,hisQueryNormalMinNum,prefixLogStr);
            //查询his返回的结果
            if(payResponse!=null&&"0".equals(payResponse.getResultCode())){
                List<PayVoResponse> payVoResponses= payResponse.getResult();
                if (payVoResponses != null && payVoResponses.size() > 0) {
                    //如果条数大于1，直接返回，不处理
                    if (payVoResponses.size() > 1) {
                        String reason = prefixLogStr + ",根据门诊订单号去前置机查询，查询的返回的条数为:" + payVoResponses.size() + ",不符合逻辑，该单不处理!";
                        Log.i(LogScene.EXCEPTION_ORDER_FILTER_CLINIC,"listClinicPay",LogParamType.EXCEPTION,
                                order.getOrderNo(),reason);
                        BaseService.getBaseClient().updateOrderExceptionReason(orderExceptionVo.getId(), orderExceptionVo.getExceptionReason() + "||||" + reason);
                        return;
                    }
                    //取第一条数据，进行数据的状态校验
                    PayVoResponse payVoResponse =payVoResponses.get(0);
                    if ("1".equals(payVoResponse.getPayStatus())) { // 查询成功，result为值，并且支付状态为已支付，成功
                        handleSuccessful(order, orderExceptionVo, payVoResponse.getHisOrdNum(),
                                payVoResponse.getHisMessage(), payVoResponse.getBarCode(),
                                payVoResponse.getReceiptNum(),prefixLogStr);
                        return;
                    } else { // 明确失败,查询成功，result为值，但支付状态不是已支付，失败
                        handleFailure(order, orderExceptionVo, null, true,prefixLogStr);
                        return;
                    }
                } else {// 明确失败，查询成功，result为空，认为写单失败，失败
                    handleFailure(order, orderExceptionVo, null, false,prefixLogStr);
                    return;
                }
            }
        }

        // 已缴费查询返回不为0，查询失败，等待下次再次查询
        int handleCount = 0;
        if (orderExceptionVo.getExceptionHandlerCount() != null) {
            handleCount = orderExceptionVo.getExceptionHandlerCount().intValue();
        }
        // 处理次数加1
        handleCount++;
        if (handleCount >= queryMaxExcepionNum) {
            String reason=prefixLogStr+"查询门诊订单异常处理超过最大次数:"+queryMaxExcepionNum+"次";
            Log.i(LogScene.EXCEPTION_ORDER_FILTER_CLINIC, orderExceptionVo.getOrderNo(),reason);
            orderExceptionVo.setExceptionReason(orderExceptionVo.getExceptionReason()+"||||"+reason);
            orderExceptionVo.setHisQueryState((short) 3);//his查询异常
            orderExceptionVo.setInsuranceHandlerFlag((short) 3);//无须处理
            orderExceptionVo.setSelfPayHandlerFlag((short) 3);//无须处理
            orderExceptionVo.setHandlerResult((short) 4);//异常单
        } else {
            orderExceptionVo.setExceptionHandlerCount(handleCount);
        }
        updateOrderException(orderExceptionVo);
    }
    
    
    /**
     * 住院异常处理
     * @param order                 订单信息
     * @param orderExceptionVo      订单异常信息
     */
    private void doInHospitalException(OrderExtVo order, OrderExceptionVo orderExceptionVo, int hisQueryNormalMinNum, int queryMaxExcepionNum, String prefixLogStr) {
        //查询his住院已缴费信息
        DepositRecordsVo depositVo = new DepositRecordsVo();
        depositVo.setHospitalCode(orderExceptionVo.getOrgCode());
        depositVo.setBranchCode(orderExceptionVo.getBranchCode());
        depositVo.setPatCardType(ObjectParser.toString(order.getMedicalCardType()));
        depositVo.setPatCardNo(order.getMedicalCardNo());
        depositVo.setPayMode(ObjectParser.toString(order.getPayMode().intValue() == 99 ? 23 : order.getPayMode()));
        depositVo.setYytOrdNum(orderExceptionVo.getOrderNo());
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, -1);
        depositVo.setBeginDate(DateUtils.getDateStr(calendar.getTime()));
        depositVo.setEndDate(DateUtils.getDateStr(new Date()));

        Map<String, String> extraParamsMap = JsonUtils.parseObject(order.getExtraParams(), Map.class);
        if(extraParamsMap != null) {
            depositVo.setAdmissionNo(extraParamsMap.get("admission_no"));
            Map<String,String> requestExtMap = new HashMap<>();
            requestExtMap.put("patient_id",extraParamsMap.get("patient_id"));
            requestExtMap.put("in_time",extraParamsMap.get("in_time"));
            depositVo.setExtendParams(JsonUtils.toJsonString(requestExtMap));
        }

        Log.i(LogScene.EXCEPTION_ORDER_FILTER_BED,"getDepositRecords(前置机住院已缴费查询)",LogParamType.REQUEST,orderExceptionVo.getOrderNo(),JSONObject.toJSONString(depositVo));
        ResCommon<List<DepositRecordsVoResponse>> payResponse = HisifaceService.getHisifaceClient().getDepositRecords(depositVo);
        Log.i(LogScene.EXCEPTION_ORDER_FILTER_BED,"getDepositRecords(前置机住院已缴费查询)",LogParamType.RESPONSE,orderExceptionVo.getOrderNo(),JSONObject.toJSONString(payResponse));
        if ("0".equals(payResponse.getResultCode())) {
            //尝试对his进行多次的查询，才能进行后续的处理
            payResponse= queryHisInHospitalResponseMinNum(depositVo,hisQueryNormalMinNum,prefixLogStr);
            //查询his返回的结果
            if (payResponse != null && "0".equals(payResponse.getResultCode())) {
                List<DepositRecordsVoResponse> payVoResponses = payResponse.getResult();
                if (payVoResponses != null && payVoResponses.size() > 0) {
                    //如果条数大于1，直接返回，不处理
                    if (payVoResponses.size() > 1) {
                        String reason = prefixLogStr + ",根据住院订单号[" + orderExceptionVo.getOrderNo() + "]去前置机查询，查询的返回的条数为:" + payVoResponses.size() + ",不符合逻辑，该单不处理!";
                        Log.i(LogScene.EXCEPTION_ORDER_FILTER_BED,orderExceptionVo.getOrderNo(),reason);
                        BaseService.getBaseClient().updateOrderExceptionReason(orderExceptionVo.getId(), orderExceptionVo.getExceptionReason() + "||||" + reason);
                        return;
                    }
                    //取第一条数据，进行数据的状态校验
                    DepositRecordsVoResponse payVoResponse = payVoResponses.get(0);
                    //TODO:原来逻辑不用考虑住院记录回来的状态吗？
                    handleSuccessful(order, orderExceptionVo, payVoResponse.getHisOrdNum(), "", payVoResponse.getBarCode(), payVoResponse.getReceiptNum(), prefixLogStr);
                } else {
                    handleFailure(order, orderExceptionVo, null, false, prefixLogStr);
                }
            }
        }

        // 已缴费查询返回不为0，查询失败，等待下次再次查询
        int handleCount = 0;
        if (orderExceptionVo.getExceptionHandlerCount() != null) {
            handleCount = orderExceptionVo.getExceptionHandlerCount().intValue();
        }
        // 处理次数加1
        handleCount++;
        if (handleCount >= queryMaxExcepionNum) {
            String reason=prefixLogStr+"查询住院订单["+orderExceptionVo.getOrderNo()+"]异常处理超过最大次数:"+queryMaxExcepionNum+"次";
            Log.i(LogScene.EXCEPTION_ORDER_FILTER_BED,orderExceptionVo.getOrderNo(),reason);
            orderExceptionVo.setExceptionReason(orderExceptionVo.getExceptionReason()+"||||"+reason);
            orderExceptionVo.setHisQueryState((short) 3);
            orderExceptionVo.setInsuranceHandlerFlag((short) 3);//无须处理
            orderExceptionVo.setSelfPayHandlerFlag((short) 3);//无须处理
            orderExceptionVo.setHandlerResult((short) 4);
        } else {
            orderExceptionVo.setExceptionHandlerCount(handleCount);
        }
        updateOrderException(orderExceptionVo);
    }

    /**
     * 出院结算异常处理
     * @param order                 订单信息
     * @param orderExceptionVo      订单异常信息
     */
    private void doOutSettlementException(OrderExtVo order, OrderExceptionVo orderExceptionVo, int hisQueryNormalMinNum, int queryMaxExcepionNum, String prefixLogStr) {
        //查询his出院结算记录
        DepositSettlementRecordsVo depositVo = new DepositSettlementRecordsVo();
        depositVo.setHospitalCode(orderExceptionVo.getOrgCode());
        depositVo.setBranchCode(orderExceptionVo.getBranchCode());
        depositVo.setPatCardType(ObjectParser.toString(order.getMedicalCardType()));
        depositVo.setPatCardNo(order.getMedicalCardNo());
        depositVo.setPayMode(ObjectParser.toString(order.getPayMode().intValue() == 99 ? 23 : order.getPayMode()));
        depositVo.setYytOrdNum(orderExceptionVo.getOrderNo());
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, -1);
        depositVo.setBeginDate(DateUtils.getDateStr(calendar.getTime()));
        depositVo.setEndDate(DateUtils.getDateStr(new Date()));

        Map<String, String> extraParamsMap = JsonUtils.parseObject(order.getExtraParams(), Map.class);
        if(extraParamsMap != null) {
            depositVo.setAdmissionNo(extraParamsMap.get("admission_no"));
            Map<String,String> requestExtMap = new HashMap<>();
            requestExtMap.put("patient_id",extraParamsMap.get("patient_id"));
            requestExtMap.put("in_time",extraParamsMap.get("in_time"));
            depositVo.setExtendParams(JsonUtils.toJsonString(requestExtMap));
        }

        Log.i(LogScene.EXCEPTION_ORDER_FILTER_BED,"getOutSettlementPayList(出院结算记录查询)",LogParamType.REQUEST,orderExceptionVo.getOrderNo(),JSONObject.toJSONString(depositVo));
        ResCommon<List<DepositSettlementRecordsVoResponse>> payResponse = HisifaceService.getHisifaceClient().getOutSettlementPayList(depositVo);
        Log.i(LogScene.EXCEPTION_ORDER_FILTER_BED,"getOutSettlementPayList(出院结算记录查询)",LogParamType.RESPONSE,orderExceptionVo.getOrderNo(),JSONObject.toJSONString(payResponse));
        if ("0".equals(payResponse.getResultCode())) {
            //尝试对his进行多次的查询，才能进行后续的处理
            payResponse= queryHisOutSettlementResponseMinNum(depositVo,hisQueryNormalMinNum,prefixLogStr);
            //查询his返回的结果
            if (payResponse != null && "0".equals(payResponse.getResultCode())) {
                List<DepositSettlementRecordsVoResponse> payVoResponses = payResponse.getResult();
                if (payVoResponses != null && payVoResponses.size() > 0) {
                    //如果条数大于1，直接返回，不处理
                    if (payVoResponses.size() > 1) {
                        String reason = prefixLogStr + ",根据住院订单号[" + orderExceptionVo.getOrderNo() + "]去前置机查询，查询的返回的条数为:" + payVoResponses.size() + ",不符合逻辑，该单不处理!";
                        Log.i(LogScene.EXCEPTION_ORDER_FILTER_BED,orderExceptionVo.getOrderNo(),reason);
                        BaseService.getBaseClient().updateOrderExceptionReason(orderExceptionVo.getId(), orderExceptionVo.getExceptionReason() + "||||" + reason);
                        return;
                    }
                    //取第一条数据，进行数据的状态校验
                    DepositSettlementRecordsVoResponse payVoResponse = payVoResponses.get(0);
                    //TODO:原来逻辑不用考虑住院记录回来的状态吗？
                    handleSuccessful(order, orderExceptionVo, payVoResponse.getHisOrdNum(), "", payVoResponse.getBarCode(), payVoResponse.getReceiptNum(), prefixLogStr);
                } else {
                    handleFailure(order, orderExceptionVo, null, false, prefixLogStr);
                }
            }
        }

        // 已缴费查询返回不为0，查询失败，等待下次再次查询
        int handleCount = 0;
        if (orderExceptionVo.getExceptionHandlerCount() != null) {
            handleCount = orderExceptionVo.getExceptionHandlerCount().intValue();
        }
        // 处理次数加1
        handleCount++;
        if (handleCount >= queryMaxExcepionNum) {
            String reason=prefixLogStr+"查询出院结算订单["+orderExceptionVo.getOrderNo()+"]异常处理超过最大次数:"+queryMaxExcepionNum+"次";
            Log.i(LogScene.EXCEPTION_ORDER_FILTER_BED,orderExceptionVo.getOrderNo(),reason);
            orderExceptionVo.setExceptionReason(orderExceptionVo.getExceptionReason()+"||||"+reason);
            orderExceptionVo.setHisQueryState((short) 3);
            orderExceptionVo.setInsuranceHandlerFlag((short) 3);//无须处理
            orderExceptionVo.setSelfPayHandlerFlag((short) 3);//无须处理
            orderExceptionVo.setHandlerResult((short) 4);
        } else {
            orderExceptionVo.setExceptionHandlerCount(handleCount);
        }
        updateOrderException(orderExceptionVo);
    }

    private void handleFailure(OrderExtVo order, OrderExceptionVo updateOrderExceptionVo, PayVoResponse payVoResponse, boolean isHisSuccess,String prefixLogStr) {
        Log.i(LogScene.EXCEPTION_ORDER_FILTER,order.getOrderNo(),prefixLogStr+"开始处理失败的异常单->" + order.getOrderNo());
        OrderExtVo updateOrderVo = new OrderExtVo();
        updateOrderVo.setUpdateTime(DateUtils.dateToString(new Date()));
        updateOrderVo.setId(order.getId());
        if (3 == order.getPayStatus().intValue()) {//订单已支付，写单失败，需要退费
            //订单表，添加支付流水
            addPaymentJournal(order);
            updateOrderVo.setOrderStatusFail();// 失败
            updateOrderVo.setPayStatusWaitRefund();// 待退费

            //订单异常表
            updateOrderExceptionVo.setHisQueryState((short) 2);//失败
            updateOrderExceptionVo.setInsuranceHandlerFlag((short) 0);//未处理
            updateOrderExceptionVo.setSelfPayHandlerFlag((short) 0);//未处理
        } else if (1 == order.getPayStatus().intValue() || 2 == order.getPayStatus().intValue()) {
            if(isHisSuccess) {
                //订单异常表
                updateOrderExceptionVo.setHisQueryState((short) 1);//查询his成功
            } else {
                updateOrderExceptionVo.setHisQueryState((short) 2);//his返回空数据，标记为失败
            }
            updateOrderVo.setOrderStatusFail();// 失败
            updateOrderExceptionVo.setInsuranceHandlerFlag((short) 3); //无须处理
            updateOrderExceptionVo.setSelfPayHandlerFlag((short) 3);  //无须处理
        } else {
            Log.i(LogScene.EXCEPTION_ORDER_FILTER,order.getOrderNo(),prefixLogStr+"处理失败的异常单,订单支付状态非已支付或未支付，不处理!");
        }

        Log.i(LogScene.EXCEPTION_ORDER_FILTER,"yyt.base.order.update",LogParamType.REQUEST,order.getOrderNo(),prefixLogStr+"处理失败的异常单,更新订单信息request->" + JSONObject.toJSONString(updateOrderVo));
        BaseService.callUnderlineFromInternal("yyt.base.order.update", JsonUtils.toJsonString(updateOrderVo));


        //更新异常订单状态
        updateOrderExceptionVo.setHandlerResult((short) 1);//查询HIS成功，重新改订单状态和入流水完成
        updateOrderException(updateOrderExceptionVo);
    }

    private void handleSuccessful(OrderExtVo order, OrderExceptionVo orderExceptionVo, String hisOrdNum, String hisMessage, String barcode, String receiptNum,String prefixLogStr) {
        Log.i(LogScene.EXCEPTION_ORDER_FILTER,order.getOrderNo(),prefixLogStr+"查询his成功，his成功返回写单状态->"+orderExceptionVo.getOrderNo());
        if (3 == order.getPayStatus().intValue()) {
            addPaymentJournal(order);

            OrderExtVo updateOrderExtVo = new OrderExtVo();
            updateOrderExtVo.setPaymentDealId(order.getPaymentDealId());
            updateOrderExtVo.setInsuranceRealAmount(order.getTotalAmount().intValue() - order.getPayAmount().intValue());
            updateOrderExtVo.setPayRealAmount(order.getPayAmount());
            updateOrderExtVo.setTotalRealAmount(order.getTotalAmount());
            updateOrderExtVo.setHisOrderNo(hisOrdNum);
            updateOrderExtVo.setHisMessage(hisMessage);
            updateOrderExtVo.setBarcode(barcode);
            updateOrderExtVo.setReceiptNum(receiptNum);
            updateOrderExtVo.setOutOrderNo(order.getOutOrderNo());
            if (order.getPayMode().intValue() == 99) {
                // 99为海鹚支付宝支付，转成对应我们系统的支付宝扫码付23
                updateOrderExtVo.setPayMode((short) 23);
            } else if (order.getPayMode().intValue() == 98) {
                // 98为海鹚微信支付，转成对应我们系统的微信扫码付13
                updateOrderExtVo.setPayMode((short) 13);
            } else {
                updateOrderExtVo.setPayMode((short) order.getPayMode().intValue());
            }
            // updateOrderExtVo.setPayTime(order.getPayTime());
            updateOrderExtVo.setId(order.getId());
            updateOrderExtVo.setOrderStatusSuccess();// 写单成功
            updateOrderExtVo.setPayStatusPayed();// 支付成功
            updateOrderExtVo.setUpdateTime(DateUtils.dateToString(new Date()));
            Log.i(LogScene.EXCEPTION_ORDER_FILTER,order.getOrderNo(),prefixLogStr+"查询his成功，his成功返回写单状态, 更新订单状态->" + JSONObject.toJSONString(updateOrderExtVo));
            BaseService.callUnderlineFromInternal("yyt.base.order.update", JsonUtils.toJsonString(updateOrderExtVo));
        } else if (1 == order.getPayStatus().intValue() || 2 == order.getPayStatus().intValue()) {
            OrderExtVo updateOrderExtVo = new OrderExtVo();
            updateOrderExtVo.setId(order.getId());
            updateOrderExtVo.setOrderStatusSuccess();// 写单成功
            updateOrderExtVo.setPayStatusAccess();//支付不成功
            updateOrderExtVo.setUpdateTime(DateUtils.dateToString(new Date()));
            Log.i(LogScene.EXCEPTION_ORDER_FILTER,order.getOrderNo(),prefixLogStr+"查询his成功，his成功返回写单状态, 更新订单状态->" + JSONObject.toJSONString(updateOrderExtVo));
            BaseService.callUnderlineFromInternal("yyt.base.order.update", JsonUtils.toJsonString(updateOrderExtVo));
        } else {
            Log.i(LogScene.EXCEPTION_ORDER_FILTER,order.getOrderNo(),prefixLogStr+"查询his成功, 订单支付状态非已支付或未支付，不处理!");
        }
        
        orderExceptionVo.setHisQueryState((short) 1);//his查询成功
        orderExceptionVo.setHandlerResult((short) 1);//查询HIS成功，重新改订单状态和入流水完成
        orderExceptionVo.setInsuranceHandlerFlag((short) 3);//无须处理
        orderExceptionVo.setSelfPayHandlerFlag((short) 3);//无须处理
        updateOrderException(orderExceptionVo);
    }

    private void addPaymentJournal(OrderExtVo order) {
        PaymentJournalVo tmp = new PaymentJournalVo();
        tmp.setOrderNo(order.getOrderNo());
        tmp.setPayStatus((short) 1);
        Log.i(LogScene.EXCEPTION_ORDER_FILTER,order.getOrderNo(),"定时异常单处理，addPaymentJournal, paymentJournal=" + JSON.toJSONString(tmp));
        Response findPaymentJournalResponse = PayService.callUnderlineFromInternal("yyt.pay.payment.journal.find",
                JsonUtils.toJsonString(tmp));
        Log.i(LogScene.EXCEPTION_ORDER_FILTER,order.getOrderNo(),"定时异常单处理，addPaymentJournal, findPaymentJournalResponse=" + JSON.toJSONString(findPaymentJournalResponse));
        if ("0".equals(findPaymentJournalResponse.getResultCode())) {
            Log.i(LogScene.EXCEPTION_ORDER_FILTER,order.getOrderNo(),"定时异常单处理，addPaymentJournal, 支付流水已存在，不再添加。");
            return;
        }
        
        PaymentJournalVo paymentJournal=new PaymentJournalVo();
        paymentJournal.setOrgId(order.getOrgId());
        paymentJournal.setOrgName(order.getOrgName());
        paymentJournal.setOrgCode(order.getOrgCode());
        paymentJournal.setBranchId(order.getBranchId());
        paymentJournal.setBranchName(order.getBranchName());
        paymentJournal.setOrderNo(order.getOrderNo());
        paymentJournal.setOutOrderNo(order.getOutOrderNo());
        paymentJournal.setPaymentDealId(order.getPaymentDealId());
        paymentJournal.setPayAmount(order.getPayAmount());
        paymentJournal.setMedicareAmount(order.getMedicareAmount());
        paymentJournal.setAccountAmount(order.getAccountAmount());
        paymentJournal.setInsuranceAmount(order.getInsuranceAmount());
        paymentJournal.setTotalAmount(order.getTotalAmount());
        paymentJournal.setPlatformId(order.getPlatformId());
        paymentJournal.setPlatformCode(order.getPlatformCode());
        paymentJournal.setPlatformName(order.getPlatformName());
        paymentJournal.setPlatformOrgAppName(order.getPlatformOrgAppName());
        paymentJournal.setPlatformOrgAppCode(order.getPlatformOrgAppCode());
        paymentJournal.setPayAppId(order.getPayAppId());
        paymentJournal.setDealAccount("");
        paymentJournal.setAccountName("");
        paymentJournal.setPayStatus((short) 1);
        paymentJournal.setHisOrderNo(order.getHisOrderNo());
        paymentJournal.setOrderType(order.getOrderType());
        paymentJournal.setCheckStatus((short)0);
        paymentJournal.setPayTime(order.getPayTime());
        
        if (order.getPayMode().intValue() == 99) {
            paymentJournal.setPayMode((short) 23);
        } else if (order.getPayMode().intValue() == 99) {
            paymentJournal.setPayMode((short) 13);
        } else {
            paymentJournal.setPayMode((short) order.getPayMode().intValue());
        }
        
        paymentJournal.setPlatformOrgAppCode(order.getPlatformOrgAppCode());
        paymentJournal.setBranchId(order.getBranchId());
        paymentJournal.setBranchName(order.getBranchName());
        paymentJournal.setSettlementStatus((short) 0);
        if (order.getInsuranceMode() != null) {
            paymentJournal.setInsuranceMode((short) order.getInsuranceMode().intValue());
        }
        paymentJournal.setBranchId(order.getBranchId());
        paymentJournal.setBranchName(order.getBranchName());
        paymentJournal.setBranchCode(order.getBranchCode());

        Log.i(LogScene.EXCEPTION_ORDER_FILTER,order.getOrderNo(),"定时异常单处理，新增支付流水请求参数->" + JSON.toJSONString(paymentJournal));
        Response addPaymentJournalResponse = PayService.callUnderlineFromInternal("yyt.pay.payment.journal.add",
                JsonUtils.toJsonString(paymentJournal));
        Log.i(LogScene.EXCEPTION_ORDER_FILTER,order.getOrderNo(),"定时异常单处理，新增支付流水返回参数->" + JSON.toJSONString(addPaymentJournalResponse));
    }

    private void updateOrderException(OrderExceptionVo orderExceptionVo) {
        orderExceptionVo.setUpdateTime(DateUtils.dateToString(new Date()));
        Log.i(LogScene.EXCEPTION_ORDER_FILTER,orderExceptionVo.getOrderNo(),"定时异常单处理，updateOrderException, orderExceptionVo=" + JSONObject.toJSONString(orderExceptionVo));
        BaseService.callUnderlineFromInternal("yyt.base.order.exception.update", JsonUtils.toJsonString(orderExceptionVo));
    }

    /**
     * 属性值的查找
     * @param orgCode 医院编码
     * @param attributeName 属性名称
     * @param defaultValue  默认值
     * @return 属性值
     */
    private int getAttributeValue(String orgCode,String attributeName,int defaultValue,String prefixLogStr){
        int value=0;
        RuleDto ruleDto=new RuleDto();
        ruleDto.setAttributeName(attributeName);
        ruleDto.setOrgCode(orgCode);
        Log.i(LogScene.EXCEPTION_ORDER_FILTER,prefixLogStr+"查询当前医院的正常需要处理的属性["+attributeName+"]才能进行退款 request->" + JSON.toJSONString(ruleDto));
        RuleResponseDto ruleResponseDto=BaseService.getBaseClient().getRule(ruleDto);
        Log.i(LogScene.EXCEPTION_ORDER_FILTER,prefixLogStr+"查询当前医院的正常需要处理的属性["+attributeName+"]才能进行退款 response->" + JSON.toJSONString(ruleResponseDto));
        if(ruleResponseDto==null){
            value=defaultValue;
        }else{
            value=ObjectParser.toInteger(ruleResponseDto.getAttributeProperties()).intValue();
        }
        return value;
    }

    /**
     * 设置成功的HIS的最小查询次数
     * @param payvo
     * @param hisQueryNormalMinNum
     * @param prefixLogStr
     * @return
     */
    private ResCommon<List<PayVoResponse>> queryHisClinicResponseMinNum(PayVo payvo,int hisQueryNormalMinNum,String prefixLogStr){
        ResCommon<List<PayVoResponse>> payResponse=null;
        for(int i=0;i<hisQueryNormalMinNum;i++){
            Log.i(LogScene.EXCEPTION_ORDER_FILTER_CLINIC,prefixLogStr + "最小有效次数:"+hisQueryNormalMinNum+"次查询，第"+(i+1)+"次请求前置机已缴费查询订单["+payvo.getYytOrdNum()+"]request->" + JSONObject.toJSONString(payvo));
            payResponse = HisifaceService.getHisifaceClient().listClinicPay(payvo);
            Log.i(LogScene.EXCEPTION_ORDER_FILTER_CLINIC,prefixLogStr + "最小有效次数:"+hisQueryNormalMinNum+"次查询，第"+(i+1)+"次请求前置机已缴费查询订单["+payvo.getYytOrdNum()+"]reseponse->" + JSON.toJSONString(payResponse));
            //休眠1分钟后，再去查his
            try {
                Thread.sleep(1000*60);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return payResponse;
    }

    /**
     * 住院次数查询的最小次数
     * @param depositVo
     * @param hisQueryNormalMinNum
     * @param prefixLogStr
     * @return
     */
    private  ResCommon<List<DepositRecordsVoResponse>> queryHisInHospitalResponseMinNum(DepositRecordsVo depositVo,int hisQueryNormalMinNum,String prefixLogStr){
        ResCommon<List<DepositRecordsVoResponse>>  payResponse=null;
        for(int i=0;i<hisQueryNormalMinNum;i++){
            Log.i(LogScene.EXCEPTION_ORDER_FILTER_BED,prefixLogStr +  "最小有效次数:"+hisQueryNormalMinNum+"次查询，第"+(i+1)+"次求前置机住院已缴费查询订单["+depositVo.getYytOrdNum()+"]request->" + JSONObject.toJSONString(depositVo));
            payResponse = HisifaceService.getHisifaceClient().getDepositRecords(depositVo);
            Log.i(LogScene.EXCEPTION_ORDER_FILTER_BED,prefixLogStr +  "最小有效次数:"+hisQueryNormalMinNum+"次查询，第"+(i+1)+"次求前置机住院已缴费查询订单["+depositVo.getYytOrdNum()+"]response->" + JSONObject.toJSONString(payResponse));
            //休眠1分钟后，再去查his
            try {
                Thread.sleep(1000*60);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return payResponse;
    }

    /**
     * 住院次数查询的最小次数
     * @param depositVo
     * @param hisQueryNormalMinNum
     * @param prefixLogStr
     * @return
     */
    private  ResCommon<List<DepositSettlementRecordsVoResponse>> queryHisOutSettlementResponseMinNum(DepositSettlementRecordsVo depositVo,int hisQueryNormalMinNum,String prefixLogStr){
        ResCommon<List<DepositSettlementRecordsVoResponse>>  payResponse=null;
        for(int i=0;i<hisQueryNormalMinNum;i++){
            Log.i(LogScene.EXCEPTION_ORDER_FILTER_BED,prefixLogStr +  "最小有效次数:"+hisQueryNormalMinNum+"次查询，第"+(i+1)+"次求前置机住院已缴费查询订单["+depositVo.getYytOrdNum()+"]request->" + JSONObject.toJSONString(depositVo));
            payResponse = HisifaceService.getHisifaceClient().getOutSettlementPayList(depositVo);
            Log.i(LogScene.EXCEPTION_ORDER_FILTER_BED,prefixLogStr +  "最小有效次数:"+hisQueryNormalMinNum+"次查询，第"+(i+1)+"次求前置机住院已缴费查询订单["+depositVo.getYytOrdNum()+"]response->" + JSONObject.toJSONString(payResponse));
            //休眠1分钟后，再去查his
            try {
                Thread.sleep(1000*60);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return payResponse;
    }

    /**
     * 设置挂号成功的HIS的最小查询次数
     * @param registerRecordsVo
     * @param hisQueryNormalMinNum
     * @param prefixLogStr
     * @return
     */
    private ResCommon<RegisterExceptionRecordVoResponse> queryHisRegisterResponseMinNum(RegisterExceptionRecordVo registerRecordsVo,int hisQueryNormalMinNum,String prefixLogStr){


        ResCommon<RegisterExceptionRecordVoResponse> payResponse=null;
        for(int i=0;i<hisQueryNormalMinNum;i++){
            Log.i(LogScene.EXCEPTION_ORDER_FILTER_REGISTER,prefixLogStr + "最小有效次数:"+hisQueryNormalMinNum+"次查询，第"+(i+1)+"次请求前置机已缴费查询订单["+registerRecordsVo.getYytOrdNum()+"]request->" + JSONObject.toJSONString(registerRecordsVo));
            payResponse = HisifaceService.getHisifaceClient().getRegisterExceptionRecord(registerRecordsVo);
            Log.i(LogScene.EXCEPTION_ORDER_FILTER_REGISTER,prefixLogStr + "最小有效次数:"+hisQueryNormalMinNum+"次查询，第"+(i+1)+"次请求前置机已缴费查询订单["+registerRecordsVo.getYytOrdNum()+"]reseponse->" + JSON.toJSONString(payResponse));
            //休眠1分钟后，再去查his
            try {
                Thread.sleep(1000*60);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return payResponse;
    }

    private void handleRegisterSuccessful(OrderExtVo order, OrderExceptionVo orderExceptionVo, RegisterExceptionRecordVoResponse recordsVoResponse,String prefixLogStr) {
        Log.i(LogScene.EXCEPTION_ORDER_FILTER_REGISTER,order.getOrderNo(),prefixLogStr+"查询his成功，his成功返回写单状态->"+orderExceptionVo.getOrderNo());
        if (3 == order.getPayStatus().intValue()) {
            addPaymentJournal(order);

            order.setReceiptNum(recordsVoResponse.getReceiptNum());
            order.setBarcode(recordsVoResponse.getBarCode());

            Map<String, String> extraParamsMap = JsonUtils.parseObject(order.getExtraParams(),Map.class);
            extraParamsMap.put("serial_num",recordsVoResponse.getSerialNum());
            extraParamsMap.put("visit_address",recordsVoResponse.getVisitLocation());
            extraParamsMap.put("visit_desc",recordsVoResponse.getVisitDesc());
            order.setExtraParams(JsonUtils.toJsonString(extraParamsMap));
            order.setOrderStatusSuccess();
            order.setUpdateTime(DateUtils.dateToString(new Date()));
//            if(org.apache.commons.lang.StringUtils.isNotBlank((String) recordsVoResponse.getOrderNo())){
//                order.setReserveNo(recordsVoResponse.getOrderNo());
//            }
            Log.i(LogScene.EXCEPTION_ORDER_FILTER_REGISTER,order.getOrderNo(),prefixLogStr+"查询his成功，his成功返回写单状态, 更新订单状态->" + JSONObject.toJSONString(order));
            BaseService.callUnderlineFromInternal("yyt.base.order.update", JsonUtils.toJsonString(order));
        } else if (1 == order.getPayStatus().intValue() || 2 == order.getPayStatus().intValue()) {
            OrderExtVo updateOrderExtVo = new OrderExtVo();
            updateOrderExtVo.setId(order.getId());
            updateOrderExtVo.setOrderStatusSuccess();// 写单成功
            updateOrderExtVo.setPayStatusAccess();//支付不成功
            updateOrderExtVo.setUpdateTime(DateUtils.dateToString(new Date()));
            Log.i(LogScene.EXCEPTION_ORDER_FILTER_REGISTER,order.getOrderNo(),prefixLogStr+"查询his成功，his成功返回写单状态, 更新订单状态->" + JSONObject.toJSONString(updateOrderExtVo));
            BaseService.callUnderlineFromInternal("yyt.base.order.update", JsonUtils.toJsonString(updateOrderExtVo));
        } else {
            Log.i(LogScene.EXCEPTION_ORDER_FILTER_REGISTER,order.getOrderNo(),prefixLogStr+"查询his成功, 订单支付状态非已支付或未支付，不处理!");
        }

        orderExceptionVo.setHisQueryState((short) 1);//his查询成功
        orderExceptionVo.setHandlerResult((short) 1);//查询HIS成功，重新改订单状态和入流水完成
        orderExceptionVo.setInsuranceHandlerFlag((short) 3);//无须处理
        orderExceptionVo.setSelfPayHandlerFlag((short) 3);//无须处理
        updateOrderException(orderExceptionVo);
    }
}
